<template>
  <div class="report-preview">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="title">{{ report?.name || '报表预览' }}</div>
      <div class="actions">
        <el-button-group>
          <el-button type="primary" @click="exportPDF">
            <i class="fas fa-file-pdf"></i> 导出PDF
          </el-button>
          <el-button type="primary" @click="exportExcel">
            <i class="fas fa-file-excel"></i> 导出Excel
          </el-button>
          <el-button type="primary" @click="exportImage">
            <i class="fas fa-file-image"></i> 导出图片
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 预览内容 -->
    <div class="preview-container" ref="previewContainer">
      <div v-for="component in report?.components" 
           :key="component.id"
           class="component-wrapper">
        <!-- 图表组件 -->
        <div v-if="component.type === 'chart'" 
             :id="'chart-' + component.id" 
             class="chart-container"
             :style="getComponentStyle(component)">
        </div>
        
        <!-- 表格组件 -->
        <div v-else-if="component.type === 'table'" 
             class="table-container"
             :style="getComponentStyle(component)">
          <el-table :data="component.data" border>
            <el-table-column v-for="col in component.columns"
                            :key="col.prop"
                            :prop="col.prop"
                            :label="col.label">
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 文本组件 -->
        <div v-else-if="component.type === 'text'"
             class="text-container"
             :style="{
               ...getComponentStyle(component),
               fontSize: `${component.fontSize || 14}px`,
               textAlign: component.textAlign || 'left'
             }"
             v-html="component.content">
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-mask">
      <el-loading background="rgba(255, 255, 255, 0.9)" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import html2canvas from 'html2canvas'

const route = useRoute()
const report = ref(null)
const loading = ref(true)
const previewContainer = ref(null)
const chartInstances = new Map()

// 加载报表数据
const loadReport = async () => {
  try {
    const response = await fetch(`/api/reports/${route.params.id}`)
    report.value = await response.json()
    
    // 初始化图表
    nextTick(() => {
      report.value.components.forEach(component => {
        if (component.type === 'chart') {
          initChart(component)
        }
      })
    })
  } catch (error) {
    ElMessage.error('加载报表失败')
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initChart = (component) => {
  const chartDom = document.getElementById(`chart-${component.id}`)
  if (!chartDom) return
  
  const chart = echarts.init(chartDom)
  chartInstances.set(component.id, chart)
  
  chart.setOption(generateChartOption(component))
}

// 生成图表配置
const generateChartOption = (component) => {
  // 使用与 ChartComponent 相同的配置生成逻辑
  // ... 
}

// 获取组件样式
const getComponentStyle = (component) => {
  return {
    width: `${component.width}px`,
    height: `${component.height}px`
  }
}

// 导出为PDF
const exportPDF = () => {
  window.print()
}

// 导出为Excel
const exportExcel = async () => {
  try {
    const response = await fetch(`/api/reports/${route.params.id}/excel`, {
      method: 'POST'
    })
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${report.value?.name || '报表'}.xlsx`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 导出为图片
const exportImage = async () => {
  try {
    const canvas = await html2canvas(previewContainer.value)
    const url = canvas.toDataURL('image/png')
    const a = document.createElement('a')
    a.href = url
    a.download = `${report.value?.name || '报表'}.png`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  loadReport()
})

onUnmounted(() => {
  // 清理图表实例
  chartInstances.forEach(chart => {
    chart.dispose()
  })
  chartInstances.clear()
})
</script>

<style scoped>
.report-preview {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--theme-bg, #f8fafc);
}

.toolbar {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--theme-container-bg, #ffffff);
  border-bottom: 1px solid var(--theme-border-color, #e2e8f0);
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: var(--theme-text-color, #1e293b);
}

.preview-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.component-wrapper {
  margin-bottom: 20px;
  background-color: var(--theme-container-bg, #ffffff);
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.chart-container,
.table-container,
.text-container {
  padding: 16px;
}

.loading-mask {
  position: fixed;
  inset: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 打印样式 */
@media print {
  .toolbar {
    display: none;
  }
  
  .preview-container {
    padding: 0;
  }
  
  .component-wrapper {
    break-inside: avoid;
    margin-bottom: 20px;
    box-shadow: none;
  }
}
</style> 